﻿namespace Devonline.Core
{
    /// <summary>
    /// 雪花算法
    /// </summary>
    public class SnowFlake
    {
        /// <summary>
        /// 唯一时间随机量
        /// 唯一时间，这是一个避免重复的随机量，自行设定不要大于当前时间戳
        /// </summary>
        private const long twepoch = 9527000L;
        /// <summary>
        /// 数据中心码
        /// </summary>
        private static long datacenterId = 0L;
        /// <summary>
        /// 机器码
        /// </summary>
        private static long machineId = 0L;
        /// <summary>
        /// 计数序号, 计数从零开始
        /// </summary>
        private static long sequence = 0L;

        /// <summary>
        /// 机器码字长
        /// </summary>
        private const long machineIdBits = 5L;
        /// <summary>
        /// 数据中心码字长
        /// </summary>
        private const long datacenterIdBits = 5L;
        /// <summary>
        /// 计数器字长，12个字节用来保存计数码
        /// </summary>
        private const long sequenceBits = 12L;

        /// <summary>
        /// 最大机器码
        /// </summary>
        private static readonly long maxMachineId = -1L ^ -1L << (int)machineIdBits;
        /// <summary>
        /// 最大数据中心码
        /// </summary>
        private static readonly long maxDatacenterId = -1L ^ (-1L << (int)datacenterIdBits);

        /// <summary>
        /// 机器码数据左移位数，就是后面计数器占用的位数
        /// </summary>
        private static readonly long machineIdShift = sequenceBits;
        /// <summary>
        /// 数据中心左移位数
        /// </summary>
        private static readonly long datacenterIdShift = sequenceBits + machineIdBits;
        /// <summary>
        /// 时间戳左移动位数就是机器码+计数器总字节数+数据字节数
        /// </summary>
        private static readonly long timestampLeftShift = sequenceBits + machineIdBits + datacenterIdBits;
        /// <summary>
        /// 一毫秒内可以产生计数，如果达到该值则等到下一微妙在进行生成
        /// </summary>
        public static readonly long sequenceMask = -1L ^ -1L << (int)sequenceBits;
        /// <summary>
        /// 最后一次的时间戳
        /// </summary>
        private static long lastTimestamp = -1L;
        /// <summary>
        /// 加锁对象
        /// </summary>
        private static readonly object syncRoot = new();
        /// <summary>
        /// 基准时间, 时间的起始值
        /// </summary>
        private static readonly DateTime startTime = new(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        /// <summary>
        /// 单实例对象
        /// </summary>
        private static SnowFlake? snowflake;

        /// <summary>
        /// 获取默认实例
        /// </summary>
        /// <returns></returns>
        public static SnowFlake Instance()
        {
            if (snowflake == null)
            {
                snowflake = new SnowFlake();
            }

            return snowflake;
        }

        /// <summary>
        /// 默认构造方法
        /// </summary>
        public SnowFlake()
        {
            Snowflakes(0L, -1);
        }
        /// <summary>
        /// 只包含机器码的构造方法
        /// </summary>
        /// <param name="machineId"></param>
        public SnowFlake(long machineId)
        {
            Snowflakes(machineId, -1);
        }
        /// <summary>
        /// 包含机器码和数据中心码的构造方法
        /// </summary>
        /// <param name="machineId"></param>
        /// <param name="datacenterId"></param>
        public SnowFlake(long machineId, long datacenterId)
        {
            Snowflakes(machineId, datacenterId);
        }

        /// <summary>
        /// 初始化机器码和数据中心码
        /// </summary>
        /// <param name="machineId"></param>
        /// <param name="datacenterId"></param>
        private static void Snowflakes(long machineId, long datacenterId)
        {
            if (machineId >= 0)
            {
                if (machineId > maxMachineId)
                {
                    throw new Exception("机器码码非法");
                }

                SnowFlake.machineId = machineId;
            }

            if (datacenterId >= 0)
            {
                if (datacenterId > maxDatacenterId)
                {
                    throw new Exception("数据中心码非法");
                }

                SnowFlake.datacenterId = datacenterId;
            }
        }

        /// <summary>
        /// 生成当前时间戳
        /// </summary>
        /// <returns>毫秒</returns>
        private static long GetTimestamp()
        {
            return (long)(DateTime.UtcNow - startTime).TotalMilliseconds;
        }

        /// <summary>
        /// 获取下一微秒时间戳
        /// </summary>
        /// <param name="lastTimestamp"></param>
        /// <returns></returns>
        private static long GetNextTimestamp(long lastTimestamp)
        {
            int count = 0;
            long timestamp = GetTimestamp();
            while (timestamp <= lastTimestamp)
            {
                //这里获取新的时间,可能会有错,这算法与comb一样对机器时间的要求很严格
                count++;
                if (count > 10)
                {
                    throw new Exception("机器的时间可能不对");
                }

                Task.Delay(1);
                timestamp = GetTimestamp();
            }

            return timestamp;
        }


        /// <summary>
        /// 获取长整形的ID
        /// </summary>
        /// <returns></returns>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "<Pending>")]
        public long GetId()
        {
            lock (syncRoot)
            {
                long timestamp = GetTimestamp();
                if (lastTimestamp == timestamp)
                {
                    //同一毫秒中生成ID
                    //用&运算计算该微秒内产生的计数是否已经到达上限
                    sequence = (sequence + 1) & sequenceMask;
                    if (sequence == 0)
                    {
                        //一毫秒内产生的ID计数已达上限，等待下一微妙
                        timestamp = GetNextTimestamp(lastTimestamp);
                    }
                }
                else
                {
                    //不同微秒生成ID
                    sequence = 0L;
                }

                if (timestamp < lastTimestamp)
                {
                    throw new Exception("时间戳比上一次生成ID时时间戳还小，故异常");
                }

                //把当前时间戳保存为最后生成ID的时间戳
                lastTimestamp = timestamp;
                long Id = ((timestamp - twepoch) << (int)timestampLeftShift)
                    | (datacenterId << (int)datacenterIdShift)
                    | (machineId << (int)machineIdShift)
                    | sequence;

                return Id;
            }
        }
    }
}
